import api from './index'

export interface Student {
  id: number
  username: string
  name: string
  email?: string
  phone?: string
  role: string
  status: string
  created_at: string
  last_login?: string
  class_id?: number
  class_name?: string
  problems_solved?: number
  total_score?: number
  acceptance_rate?: number
  rank?: number
  notes?: string
}

export interface CreateStudentRequest {
  username: string
  password: string
  name: string
  email?: string
  phone?: string
  class_id?: number
  notes?: string
}

export interface UpdateStudentRequest {
  name?: string
  email?: string
  phone?: string
  status?: string
  class_id?: number
  notes?: string
}

export interface BatchCreateStudentRequest {
  students: Array<{
    username: string
    password?: string
    name: string
    email?: string
    phone?: string
    class_id?: number
  }>
}

export interface StudentStats {
  total_students: number
  active_students: number
  suspended_students: number
  graduated_students: number
  average_score: number
  total_problems_solved: number
}

// 获取所有学生
export function getStudents(params?: {
  role?: string
  status?: string
  class_id?: number
  page?: number
  size?: number
}) {
  return api.get<Student[]>('/admin/users', { params })
}

// 获取学生统计信息
export function getStudentStats() {
  return api.get<StudentStats>('/admin/statistics/students')
}

// 获取单个学生信息
export function getStudent(id: number) {
  return api.get<Student>(`/admin/users/${id}`)
}

// 创建学生
export function createStudent(data: CreateStudentRequest) {
  return api.post<Student>('/auth/register', {
    ...data,
    role: 'student'
  })
}

// 批量创建学生
export function batchCreateStudents(data: BatchCreateStudentRequest) {
  return api.post<{
    success_count: number
    failed_count: number
    failed_students: Array<{
      username: string
      name: string
      error: string
    }>
  }>('/auth/batch-register', data)
}

// 更新学生信息
export function updateStudent(id: number, data: UpdateStudentRequest) {
  return api.put<Student>(`/admin/users/${id}`, data)
}

// 删除学生
export function deleteStudent(id: number) {
  return api.delete(`/admin/users/${id}`)
}

// 切换学生状态
export function toggleStudentStatus(id: number, status: string) {
  return api.put<Student>(`/admin/users/${id}`, { status })
}

// 获取班级学生
export function getClassStudents(classId: number) {
  return api.get<Student[]>(`/classes/${classId}/students`)
}

// 添加学生到班级
export function addStudentToClass(classId: number, studentIds: number[]) {
  return api.post(`/classes/${classId}/students`, { student_ids: studentIds })
}

// 从班级移除学生
export function removeStudentFromClass(classId: number, studentId: number) {
  return api.delete(`/classes/${classId}/students/${studentId}`)
}
